﻿using UnityEngine;
using System.Collections;
using System;

public class LinkController : MonoBehaviour {
	protected Animator m_animator;
	protected CharacterController m_characterController;
	protected float m_horizontalSpeed;
	protected float m_verticalSpeed;
	
	public float Gravity = 9.81f;
	public float MaxRunningPercent = 1.0f;
	public float MaxWalkingPrecent = 0.5f;
	
	float ComputeSpeed(InputState input)
	{
		// This is a multiplier that is either 1 or -1.
		// This allows us to account for the direction
		// that the user has the control stick.
		float speedDirectionMultiplier = 1;
		if (input.LeftStick.y < 0) 
		{
			speedDirectionMultiplier = -1;
		}
		
		// This accounts for the direction we have our joystick.
		float speed = speedDirectionMultiplier * input.LeftStick.magnitude;
		
		// Get a list of the connected joysticks.
		string[] joystickNames = Input.GetJoystickNames();
		
		// Default to the walking speed percent
		float maxSpeed = MaxWalkingPrecent;
		if (joystickNames.Length > 0 ||
			input.Run) 
		{
			maxSpeed = MaxRunningPercent;
		}
		
		// We want this to be a smooth transition between speeds.
		// We shoudln't jump between the speeds.
		m_horizontalSpeed = Mathf.Lerp(m_horizontalSpeed, Mathf.Clamp(speed, -maxSpeed, maxSpeed), 0.5f);
		
		// Valid values for speed are between -1 and 1.
		return m_horizontalSpeed;
	}
	
	// We probably want to do our physics stuff here.
	void FixedUpdate()
	{
		// This checks if the character controller is touching
		// a terrian object.
		if (!m_characterController.isGrounded) 
		{
			// We want to apply a negative gravity so that we
			// subtract from the z transformation instead of 
			// add to it.  This makes the character fall
			// instead of float.
			// We also need to multiply by the time and add
			// the vertical speed from the last time since
			// gravity is an acceleration.
			m_verticalSpeed += -Gravity * Time.deltaTime;
		}
		
		// We should move by the character's vertical speed.
		// We need to know how much to move in this update.
		m_characterController.Move(new Vector3(0, m_verticalSpeed * Time.deltaTime, 0));
	}
	
	// Use this for initialization
	void Start () 
	{
		// Get the animator component of the current 
		// game object.
		m_animator = GetComponent<Animator>();
		
		// This gets the character controller component
		// for the current game object.
		m_characterController = GetComponent<CharacterController>();
	}
	
	// Update is called once per frame
	void Update ()
	{				
		// Represents our input device.
		InputState input = InputState.GetInputState ();

		// Set the animator's roll variable
		m_animator.SetBool("Roll", input.Attack);
	
		// Set the animator's speed variable to our computed speed.
		m_animator.SetFloat("Speed", ComputeSpeed(input));
		// Pass the direction directly into the direction component
		// of our animator.
		m_animator.SetFloat("Direction", input.LeftStick.x);
	}
}
